// miniprogram/pages/admin/order/order.js
const app = getApp();
const util = require('../../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeTabIndex: 'all',

    list: [{
      status: 'all',
      text: '加载中...',
      num: 0
    }, ],
    statusMap: app.globalData.statusMap,
    statusText: app.globalData.statusText
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let title = options.status ? `${this.data.statusText[options.status]}订单` : '订单中心'
    let isall = options.status ? false : true
    wx.setNavigationBarTitle({
      title,
    })
    app.login(user=>{
      if (!user.studioid) {
        wx.navigateBack();
        return;
      }
      if (isall) {
        this.listOrder(user.studioid);
      }
      this.setData({
        isall,
        activeTabIndex: options.status ? options.status : 'all'
      }, res => {
        this.loadItems(true);
      })
    })
  },

  listOrder: function (studioid) {
    const that = this;
    wx.cloud.callFunction({
      name: 'order',
      data: {
        op: 'list',
        studioid: studioid
      },
      success: res => {
        let list = []; //that.data.statusText;
        let sum = 0;
        res.result.list.map((v, i) => {
          list.push({
            status: v._id,
            text: this.data.statusText[v._id],
            num: v.num
          });
          sum += v.num;
        })
        list.unshift({
          status: 'all',
          text: this.data.statusText.all,
          num: sum
        })
        that.setData({
          list
        });
      }
    })
  },

  loadItems: function (reload) {
    wx.showNavigationBarLoading();
    const that = this;
    reload = !!reload;
    let where = {
      studioid: app.globalData.user.studioid
    };
    if (this.data.activeTabIndex != 'all') {
      where.status = parseInt(this.data.activeTabIndex)
    }
    if (this.options.customerid) {
      where.customer = {
        _id: options.customerid
      };
    }
    wx.cloud.callFunction({
      name: 'crud',
      data: {
        op: 'get',
        table: 'order',
        where: where,
        skip: reload ? 0 : this.data.items.length
      },
      success: res => {
        wx.stopPullDownRefresh();
        wx.hideNavigationBarLoading();
        if (reload) {
          that.setData({
            items: res.result.data
          });
        } else {
          that.setData({
            items: that.data.items.concat(res.result.data)
          });
        }
      }
    })
  },

  // 页面跳转
  redirect: function (e) {
    let url = e.currentTarget.dataset.value;
    let _id = e.currentTarget.dataset._id;
    wx.navigateTo({

      url: `${url}?_id=${_id}`,
    });
  },

  changeStatus: function (e) {
    const that = this;
    let index = e.currentTarget.dataset.index;
    let orders = this.data.items;
    let order = orders[index];

    wx.cloud.callFunction({
      name: 'order',
      data: {
        op: 'changeStatus',
        log: {
          time: util.formatTime(new Date()),
          user: app.globalData.user.name,
          text: `${e.currentTarget.dataset.text}`
        },
        _id: order._id,
        status: parseInt(e.currentTarget.dataset.value),
      },
      success: res => {
        console.log(res);
        that.loadItems(true);
        if (that.data.isall){
          that.listOrder(app.globalData.user.studioid);
        }
      }
    })
  },
  removeOrder: function (e) {
    let that = this
    let _id = e.currentTarget.dataset._id;
    // TODO 废弃订单
    wx.showModal({
      content: '您确定要删除此订单吗？',
      success: res => {
        if (res.confirm) {
          wx.cloud.callFunction({
            name: 'order',
            data: {
              op: 'remove',
              _id: _id
            },
            success: rr => {
              that.loadItems(true);
              if (that.data.isall){
                that.listOrder(app.globalData.user.studioid);
              }
              // let pages = getCurrentPages();
              // if (pages.length > 1) {
              //   pages[pages.length - 2].onLoad(pages[pages.length - 2].options);
              // }
              // wx.navigateBack();
            }
          })

        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  changeTab(e) {
    let status = e.currentTarget.dataset.index;
    this.setData({
      activeTabIndex: status
    }, res => {
      this.loadItems(true);
    });
    // if (status != 'all'){
    //   this.loadItems(true);
    // }else{
    //   this.loadItems({}, true);
    // }

    // let activeTabIndex = e.currentTarget.dataset.index
    // console.log(activeTabIndex)
    // this.setData({
    //   activeTabIndex
    // })
  },
  showModal(e) {
    let modalname = e.currentTarget.dataset.modalname
    this.setData({
      modalname
    })

  },
  hideModal() {
    this.setData({
      modalname: null
    });
  },
  requestSubscribeMessage(e) {
    app.requestOrderSubscribeMessage()
    wx.navigateTo({
      url: e.currentTarget.dataset.url,
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log('yincang')
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('xiezai')
    let pages = getCurrentPages();

    if (pages.length > 1) {
      pages[pages.length - 2].onLoad(pages[pages.length - 2].options);
    }
    // wx.navigateBack();

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.listOrder(app.globalData.user.studioid);
    this.loadItems(true);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.items.length % 20 == 0) {
      this.loadItems(false);
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})